import { onLoad, onShow } from "@dcloudio/uni-app";
import { ref } from "vue";
import { moduleTypeRule, objectAny } from "../../options/base";
import { changeOrderStatus } from "../../utils/doCloud";
import { wxStartPay } from "../../utils/payCloud";
import { goToPage, showModal, showToast, timeOut } from "../../utils/utils";
import { toggleModule,verifyModuleList} from "../../utils/toggleModule";


const _defaultData={
    diff_count_down:-1,
    order_all_money:`默认数据`,
    menu_id:[{
        menu_name:`默认数据`
    }]
}

let orderId=``;
// 结算模块 由哪里模块跳过来的
let module:moduleTypeRule=`foodTakeout`;
let showCountDownEnd=true;
let payBtnStatus:'ready'|'padding'=`ready`;
const loading = ref(true);
const orderData=ref<objectAny>(_defaultData) 


/**
 * 初始化全家变量的参数
 */
function initResetArgs(){
    orderId=``;
    showCountDownEnd=true;
    payBtnStatus=`ready`;
    loading.value=true;
    orderData.value=_defaultData;
}


/**
 * 获取订单信息
 */
async function getOrderInfo (){
    try {
        const orderInfo=await toggleModule[module].getOrderDetails(orderId) as objectAny
        // 只有在未支付状态下的订单才可以进入显示并且可以支付
        // 这里的 rider_order_status 字段是在获取参数后前端组装的 兼容之前的 rider_order_status 字段
        // 代取模块是 rider_order_status 字段
        // 美食模块是 order_status 字段
        // 现在统一使用 rider_order_status 字段
        if(orderInfo.rider_order_status===8){
            orderInfo.diff_count_down= orderInfo.order_out_time-orderInfo.serverNowTime
            orderInfo.order_all_money=(+orderInfo.order_all_money).toFixed(2)
            orderData.value=orderInfo;
        }else{
        //其他状态的订单直接告知用户 并且跳转到订单记录页面中 
            await showModal({
                showCancel: false,
                title: `温馨提示`,
                content: `该订单已过期，点我去查看`
            })
            goToPage({
                path:`/generalUser/myOrder/myOrder`,
                navType:`replace`,
                params:{
                    t:0
                }
            })
        }
        
        loading.value=false;
        console.log(orderInfo)
    } catch (error) {
        console.error(`xxxxxx=> getOrderInfo 获取订单信息失败， 失败原因如下： <=xxxxxx`)
        console.error();
    }
}

export default {
    setup() {
        initResetArgs();
        
        onLoad(async (options:objectAny)=>{
            const queryModule=options.module;
            orderId =options.order_id||''
            module=queryModule;
            if(orderId==``||!verifyModuleList.includes(queryModule)){
                await showModal({
                    showCancel: false,
                    title: `订单异常`,
                    content: `订单异常，请重新下单`
                })
                goToPage({
                    path:`/common/tabbar1/tabbar1`,
                    navType:`pushTab`
                })

            }
            getOrderInfo();
        })


        const countDownEnd = async () => {
            if(!showCountDownEnd){
                return false
            }

            const moduleData=toggleModule[module];
            await Promise.allSettled([
                changeOrderStatus(moduleData.tableName,orderId,moduleData.buildUpdate(10)),
                showModal({
                    showCancel: false,
                    title: `订单超时`,
                    content: `订单已取消，请重新下单`
                })
            ])
            goToPage({
                path:`/generalUser/myOrder/myOrder`,
                navType:`replace`,
                params:{
                    t:2
                }
            })
        }
        const radioChange = () => {

        }

        const startPay=async ()=>{
            try {
                if(payBtnStatus===`padding`){
                    return false
                }
                payBtnStatus=`padding`;
                const {myErrCode,errMsg,data:orderInfo} =await wxStartPay(orderId,module,true);
                console.log(orderInfo)
    
                if(myErrCode!==0){
                    showCountDownEnd=false;
                    await showModal({
                        title:`异常提示`,
                        content:errMsg,
                        showCancel:false
                    }) 
                }
                if(myErrCode===10001||myErrCode===10002 ){      // 非法访问 直接强行退出
                    return goToPage({
                        navType:`replaceAll`,
                        path:`/common/mainEnter/mainEnter`
                    },true)
                }
    
                if(myErrCode===10003||myErrCode===10004||myErrCode===10005||myErrCode===10006){
                    return goToPage({
                        navType:`pushTab`,
                        path:`/common/tabbar1/tabbar1`
                    })
                }
                // 服务器端发生异常
                if(myErrCode===20000){
                    return goToPage({
                        navType:`replace`,
                        path:`/generalUser/myOrder/myOrder`,
                        params:{
                            t:0
                        }
                    })
                }
    
                if(myErrCode!==0){
                    payBtnStatus=`ready`;
                    return false
                }
    
                uni.requestPayment({
                    provider:`wxpay`,
                    ...orderInfo,
                    success:async ()=>{
                        showToast(`付款成功`,`success`);
                        await timeOut(1000);
                        goToPage({
                            navType:`replace`,
                            path:`/generalUser/myOrder/myOrder`,
                            params:{
                                t:0
                            }
                        })
                    },
                    fail:(e:objectAny)=>{
                        // errMsg: "requestPayment:fail cancel"
                        showToast(`您已取消付款`,`none`);
                        payBtnStatus=`ready`;
                    }
                })
            } catch (error) {
                payBtnStatus=`ready`;
            }

        }

        return {
            orderData,
            loading,
            startPay,
            radioChange,
            countDownEnd
        };
    }
}